package factorytest.iflytek.com.einkiflytekfactorytest.common;

import factorytest.iflytek.com.einkiflytekfactorytest.utils.FileReadWrite;

/**
 * Created by sst on 2018/11/2.
 */

public class LedCtrl {

    private static final int LED_RED = 1;
    private static final int LED_GREEN = 2;
    private static final String LEDS_PATH = "/sys/class/htfyun_leds/leds";

    private static Object priorityObject;

    public static void setLedPriority(Object priorityObj, boolean on, LedAttr... ledAttrs) {

        priorityObject = priorityObj;
        doSetLed(on, ledAttrs);

    }

    public static void setLed( boolean on, LedAttr... ledAttrs) {

        if (priorityObject != null) {
            return;
        }
        doSetLed(on, ledAttrs);

    }

    public static void doSetLed( boolean on, LedAttr... ledAttrs) {

        if (ledAttrs == null || ledAttrs.length == 0) {
            return;
        }
        closeConfigForLed();

        int id = 0;
        for (LedAttr attr : ledAttrs) {
            id |= attr.getLedId();
        }

        writeLed(id, on);

    }

    //led 本来是为了充电才显示的. 所以在这里测试led时, 内核在充电下是不去控制led的了.
    //所以我们这里要关闭他.
    private static void closeConfigForLed() {
        int led = 0xff - LED_RED - LED_GREEN;
        writeLed(led, false);

    }


    private static void writeLed(int led, boolean on) {
        String keyValue = led + "," + (on ? "1" : "0");
        FileReadWrite.writeStringToFile(LEDS_PATH, keyValue);
    }

    public enum LedAttr {

        led_red(LED_RED),
        led_green(LED_GREEN),
        ;

        private final int ledId;
        private LedAttr(int id) {
            ledId = id;
        }

        private int getLedId() {
            return ledId;
        }

    }
}
